#include <locale.h>

#include "Heap.h"

void HeapSort(int* a, size_t sz)
{
    for(int i = (sz - 2) / 2; i >= 0; i--)
        AdjustDown(a, sz, i);
    size_t end = sz - 1;
    while (end)
    {
        Swap(&a[0], &a[end]);
        AdjustDown(a, end, 0);
        end--;
    }
}

void CreateNDate()
{
    int n = 10000;
    srand(time(0));
    const char* file = "C:\\Users\\lwj12\\Downloads\\data.txt";
    FILE* fin = fopen(file, "w");
    if (fin == NULL)
    {
        perror("fopen error");
        return;
    }

    for (size_t i = 0; i < n; ++i)
    {
        int x = rand() % 1000000;
        fprintf(fin, "%d\n", x);
    }

    fclose(fin);
}

void PrintTopK(int k)
{
    FILE * file = fopen("C:\\Users\\lwj12\\Downloads\\data.txt", "r");
    if(file == NULL)
    {
        perror("fopen fail");
        return;
    }
    int* a = (int *)malloc(k * sizeof(int));
    if(a == NULL)
    {
        perror("mallco fail");
        free(a);
        fclose(file);
        return;
    }
    int val = 0;
    for (int i = 0; i < k; i++)
    {
        if (fscanf(file, "%d", &val) != EOF)  a[i] = val;
        else
        {
            perror("fscanf fail");
            fclose(file);
            free(a);
            return;
        }
    }
    for (int father = (k - 2) / 2; father >= 0; father--)
        AdjustDown(a, k, father);
    while (fscanf(file, "%d", &val) != EOF)
        if(val > a[0])
        {
            a[0] = val;
            AdjustDown(a, k, 0);
        }
    for (int i = 0; i < k; i++)
        printf("%d ", a[i]);
    free(a);
    fclose(file);
}

int main(void)
{
    CreateNDate();

    printf("请输入k : > ");
    int k;
    scanf("%d", &k);
    PrintTopK(k);

    /*int a[] = {4,7,1,77,22,44,23,53,2,6,7};
    size_t sz = sizeof(a) / sizeof(a[0]);
    HeapSort(a, sz);*/

    /*Heap HP;
    HPInit(&HP);
    for(int i = 0; i < sizeof(arr) / sizeof(arr[0]); i++)
        HPPush(&HP, arr[i]);
    while (! HPEmpty(&HP))
    {
        int i = HPTop(&HP);
        printf("%d ", i);
        HPPop(&HP);
    }*/
    return 0;
}
